<template>
  <el-dialog
    ref="el-dialog"
    :title="`${isEdit ? '编辑' : '新增'}传感器基站`"
    :visible.sync="dialogVisible"
    width="1001px"
    :close-on-click-modal="false"
    :before-close="close"
  >
    <div>
      <el-form ref="RefForm" :model="formData" label-width="120px" :inline="true" :validate-on-rule-change="false" :rules="formRules" status-icon>
        <div id="map" class="divTwo" @click="getCoordinateHandler">
          <p class="messg">点击图片可直接添加设备定位点</p>
          <div
            class="divS"
            :style="{
              display: formData.x || formData.y ? 'block' : 'none',
              left: formData.x / 1.5 + 'px',
              top: formData.y / 1.5 + 'px'
            }"
          >
            <img :src="sensorImg" alt="环境监测设备" />
          </div>
          <!-- 基站 -->
          <template v-for="item in baseStationList">
            <el-popover
              :key="item.id"
              placement="top-start"
              class="up"
              :style="{ left: item.x / 1.5 + 'px', top: item.y / 1.5 + 'px', zIndex: 10 }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">基站名称:</span>
                <span class="deep">{{ item.name }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">基站类型:</span>
                <span class="deep">{{ item.siteType }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">区域:</span>
                <span class="deep">{{ item.areaName }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">状态:</span>
                <span class="deep">{{ item.status }}</span>
              </div>
              <!-- <div class="labelDiv">
                <span class="shallow">考勤机站:</span>
                <span class="deep">{{ item.isForWorkCheck ? '是' : '否' }}</span>
              </div>-->
              <img slot="reference" :src="iconData[0].value" alt="基站" />
            </el-popover>
          </template>
          <!-- 基站覆盖范围 -->
          <template v-for="baseStation in baseStationList">
            <el-popover
              :key="baseStation.name"
              placement="top-start"
              class="range"
              :style="{
                width: baseStation.widthPosition / 1.5 + 'px',
                height: baseStation.heightPosition / 1.5 + 'px',
                transform: 'rotateZ(' + baseStation.rotate + 'deg)',
                left: baseStation.leftPosition / 1.5 + 'px',
                top: baseStation.topPosition / 1.5 + 'px'
              }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">范围归属:</span>
                <span class="deep">{{ baseStation.name }}</span>
              </div>
              <div
                slot="reference"
                :style="{
                  width: baseStation.widthPosition / 1.5 + 'px',
                  height: baseStation.heightPosition / 1.5 + 'px',
                  border: 'none'
                }"
                class="range"
              ></div>
            </el-popover>
          </template>
          <!-- 监控设备 -->
          <template v-for="cameraItem in videoList">
            <el-popover
              v-if="cameraItem.name !== formData.name"
              :key="cameraItem.id"
              placement="top-start"
              class="cameraItem"
              :style="{ left: cameraItem.x / 1.5 + 'px', top: cameraItem.y / 1.5 + 'px' }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">监控名称:</span>
                <span class="deep">{{ cameraItem.name }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">区域:</span>
                <span class="deep">{{ cameraItem.area ? cameraItem.area.name : '无' }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">状态:</span>
                <span class="deep">{{ cameraItem ? cameraItem.status : '' }}</span>
              </div>
              <img slot="reference" :src="iconData[1].value" alt="监控" />
            </el-popover>
          </template>
          <!-- 环境监测设备 -->
          <template v-for="environmentalItem in environmentalList">
            <el-popover
              v-if="environmentalItem.name !== formData.name"
              :key="environmentalItem.id"
              placement="top-start"
              class="cameraItem"
              :style="{ left: environmentalItem.x / 1.5 + 'px', top: environmentalItem.y / 1.5 + 'px' }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">监测设备:</span>
                <span class="deep">{{ environmentalItem.name }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">设备IP:</span>
                <span class="deep">{{ environmentalItem.ip }}</span>
              </div>
              <template v-if="environmentalItem.settingItems.length > 0">
                <div v-for="(project, projectIndex) in environmentalItem.settingItems" :key="project.key" class="labelDiv">
                  <span v-if="projectIndex === 0" class="shallow">监测项目:</span>
                  <span v-else class="shallowTwo"></span>
                  <span class="deep">{{ project.key ? project.key : '无' }}；</span>
                </div>
              </template>
              <template v-else>
                <div class="labelDiv">
                  <span class="shallow">监测项目:</span>
                  <span class="deep">无</span>
                </div>
              </template>
              <img slot="reference" :src="iconData[2].value" alt="环境监测设备" />
            </el-popover>
          </template>
          <!-- 闸机覆盖范围 -->
          <template v-for="gatesItem in gatesList">
            <el-popover
              :key="gatesItem.name"
              placement="top-start"
              class="range"
              :style="{
                width: gatesItem.widthPosition / 1.5 + 'px',
                height: gatesItem.heightPosition / 1.5 + 'px',
                transform: 'rotateZ(' + gatesItem.rotate + 'deg)',
                left: gatesItem.leftPosition / 1.5 + 'px',
                top: gatesItem.topPosition / 1.5 + 'px'
              }"
              trigger="hover"
            >
              <div class="labelDiv">
                <span class="shallow">范围归属:</span>
                <span class="deep">{{ gatesItem.name }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">闸机类型:</span>
                <span class="deep">{{ gatesItem.siteType }}</span>
              </div>
              <div class="labelDiv">
                <span class="shallow">区域:</span>
                <span class="deep">{{ gatesItem.areaName }}</span>
              </div>
              <div
                slot="reference"
                :style="{
                  width: gatesItem.widthPosition / 1.5 + 'px',
                  height: gatesItem.heightPosition / 1.5 + 'px',
                  border: 'none'
                }"
                class="range"
              ></div>
            </el-popover>
          </template>
          <img v-if="mapSwaitch" class="mapImg" :src="imgSrc + mapUrl" />
          <img v-else class="mapImg" :src="mapUrl" alt />
        </div>
        <el-form-item label="基站名称" prop="name">
          <el-input v-model="formData.name" style="width: 300px" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="基站编号" prop="code">
          <el-input v-model="formData.code" style="width: 300px" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="坐标X" prop="name">
          <el-input v-model="formData.x" style="width: 300px" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="坐标Y" prop="code">
          <el-input v-model="formData.y" style="width: 300px" show-word-limit></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <template>
              <el-table :data="formData.settingItems" style="width: 100%">
                <el-table-column label="监测项" align="center" width="200">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row.label" class="alert-label"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="编码" align="center" width="200">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row.labelValue" class="alert-label"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="单位" align="center" width="120">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row.unit" class="alert-value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="报警设置" align="center" width="300">
                  <template slot-scope="scope">
                    <el-input v-model.number="scope.row.minValue" class="alert-value"></el-input>
                    <span>&lt;正常值&lt;</span>
                    <el-input v-model.number="scope.row.maxValue" class="alert-value"></el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-popconfirm title="确定删除吗？" @confirm="handleDelete(scope.$index, scope.row)">
                      <el-button slot="reference" size="mini" type="danger">删除</el-button>
                    </el-popconfirm>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button style="float: left" type="primary" @click="addHandler">新 增</el-button>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="loadingSubmit" type="primary" @click="submitHandler">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import dialogEditMixin from '@/mixins/dialogEdit'
  import { eleValidator } from '@/utils/tools'
  import { tunnel, parameter, tunnelRealTime } from '@/api/api'
  import { assetsImages } from '@/utils/images'
  import { localhostUrl } from '@/utils/setUrl.js'
  export default {
    mixins: [dialogEditMixin],
    data() {
      function AlertProp(name) {
        return [
          { required: true, message: `请输入${name}`, trigger: 'blur' },
          {
            validator: eleValidator([{ rule: 'isEmpty', msg: `${name}不能为空` }]),
            trigger: 'blur'
          }
        ]
      }
      return {
        sensorImg: assetsImages.sensor,
        imgUrl: '',
        mapUrl: '',
        imgSrc: localhostUrl + '/',
        mapSwaitch: true,
        // 地图：单洞
        singleHole: assetsImages.singleHole,
        // 地图：双洞
        doubleHole: assetsImages.doubleHole,
        deleteSettingItems: [],
        settingItems: [
          { label: '湿度', labelValue: 'shidu', unit: '%', minValue: '-50', maxValue: '50', isDelete: false },

          { label: '温度', labelValue: 'wendu', unit: '℃', minValue: '-50', maxValue: '50', isDelete: false },

          { label: '一氧化碳', labelValue: 'CO', unit: 'ppb', minValue: '0', maxValue: '50', isDelete: false },

          { label: '二氧化碳', labelValue: 'CO2', unit: 'ppb', minValue: '0', maxValue: '50', isDelete: false },

          { label: '氧气', labelValue: 'O2', unit: 'ppb', minValue: '0', maxValue: '50', isDelete: false },

          { label: '二氧化氮', labelValue: 'NO2', unit: 'ppb', minValue: '0', maxValue: '50', isDelete: false },

          { label: '噪声', labelValue: 'zaosheng', unit: 'dB', minValue: '0', maxValue: '150', isDelete: false }
        ],
        formRules: {
          // 位置X
          x: [
            { required: true, message: '请输入坐标X', trigger: 'change' },
            {
              validator: eleValidator([
                { rule: 'isIp', msg: '只能输入数字' },
                { rule: 'isMapWidth', msg: '不能大于地图宽度1200，或小于0' },
                { rule: 'isEmpty', msg: '位置X不能为空' }
              ]),
              trigger: 'change'
            }
          ],
          // 位置Y
          y: [
            { required: true, message: '请输入坐标Y', trigger: 'change' },
            {
              validator: eleValidator([
                { rule: 'isIp', msg: '只能输入数字' },
                { rule: 'isMapHeight', msg: '不能大于地图宽度617，或小于0' },
                { rule: 'isEmpty', msg: '位置Y不能为空' }
              ]),
              trigger: 'change'
            }
          ],
          name: [
            { required: true, message: '请输入基站名称', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '基站名称不能为空' },
                {
                  rule: 'isRepeat',
                  msg: { value: '基站名称重复', url: '/EnvironmentTrackingSetting/Exists', key: 'name' }
                }
              ]),
              trigger: 'blur'
            }
          ],
          code: [
            { required: true, message: '请输入基站编号', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '基站编码不能为空' },
                {
                  rule: 'isRepeat',
                  msg: { value: '基站编码重复', url: '/EnvironmentTrackingSetting/Exists', key: 'code' }
                },
                { rule: 'isNumberLetter', msg: '只能输入数字和字母' }
              ]),
              trigger: 'blur'
            }
          ],
          ip: [
            { required: true, message: '请输入基站IP', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '基站IP不能为空' },
                { rule: 'isRepeat', msg: { value: '基站IP重复', url: '/EnvironmentTrackingSetting/Exists', key: 'ip' } },
                { rule: 'isIp', msg: '只能输入数字和点' }
              ]),
              trigger: 'blur'
            }
          ],
          port: [
            { required: true, message: '请输入基站端口', trigger: 'blur' },
            {
              validator: eleValidator([
                { rule: 'isEmpty', msg: '基站端口不能为空' },
                { rule: 'isNumber', msg: '只能输入数字' }
              ]),
              trigger: 'blur'
            }
          ],
          humidityLabel: AlertProp('湿度'),
          humidityAlertValue: AlertProp('湿度'),
          temperatureLabel: AlertProp('温度'),
          temperatureAlertValue: AlertProp('温度报警值'),
          coLabel: AlertProp('一氧化碳'),
          coAlertValue: AlertProp('一氧化碳报警值'),
          cO2Label: AlertProp('二氧化碳'),
          cO2AlertValue: AlertProp('二氧化碳报警值'),
          o2Lable: AlertProp('氧气'),
          humido2AlertValueityLabel: AlertProp('氧气报警值'),
          nO2Lable: AlertProp('二氧化氮'),
          nO2AlertValue: AlertProp('二氧化氮报警值'),
          noiseLable: AlertProp('噪声'),
          noiseAlertValue: AlertProp('噪声报警值')
        },
        apiKey: {
          search: '/EnvironmentTrackingSetting/',
          add: '/EnvironmentTrackingSetting',
          put: '/EnvironmentTrackingSetting/'
        },
        // 闸机
        gatesList: [],
        // 监控
        videoList: [],
        // 基站
        baseStationList: [],
        // 图标数据
        iconData: [
          { name: 'BaseStationImage', value: '', id: null }, // 基站
          { name: 'MonitorImage', value: '', id: null }, // 监控
          { name: 'AccessControlImage', value: '', id: null } // 环境监测设备
        ],
        // 环境检测设备
        environmentalList: []
      }
    },
    watch: {
      dialogVisible: function (newValue, oldValue) {
        if (newValue) {
          return
        }
        this.$refs.RefForm.clearValidate()
      }
    },
    methods: {
      responseDataHandleProgram(res) {
        console.log(res)
        let formKeys = Object.keys(this.formData)
        formKeys.forEach(item => {
          this.formData[item] = res.data[item]
        })
        // 编辑时保存ID
        this.formData.id = res.data.id
        if (res.data.settingItems && res.data.settingItems.length !== 0) {
          this.formData.settingItems = []
          res.data.settingItems.forEach(item => {
            if (!item.isDelete) {
              this.formData.settingItems.push(item)
            }
          })
        } else {
          this.formData.settingItems = this.settingItems
        }
      },
      addHandler() {
        this.formData.settingItems.push({
          label: '',
          unit: '',
          minValue: '',
          maxValue: ''
        })
      },
      handleDelete(value) {
        this.formData.settingItems[value].isDelete = true
        let obj = this.formData.settingItems.splice(value, 1)
        this.deleteSettingItems.push(obj[0])
      },
      submitHandler() {
        let ary = []
        this.deleteSettingItems.forEach((grind, index) => {
          if (!grind.label) {
            ary.push(index)
          }
        })
        if (ary.length > 0) {
          let keyList = Object.keys(ary)
          for (let i = keyList.length; i > -1; i--) {
            if (!this.deleteSettingItems[ary[i]].label) {
              this.deleteSettingItems.splice(i, 1)
            }
          }
        }
        let flag = false
        this.formData.settingItems.forEach((item, itemIndex) => {
          this.formData.settingItems.forEach((edit, editIndex) => {
            if ((itemIndex !== editIndex && item.label === edit.label) || !item.label) {
              flag = true
            }
          })
        })
        if (flag) {
          this.$message.warning('监测项不能为空或重复，请修改！')
          return
        }
        this.deleteSettingItems.forEach(setting => {
          this.formData.settingItems.push(setting)
        })
        this.handleSubmit()
      },
      resetFormData() {
        this.formData = {
          name: '',
          code: '',
          ip: '',
          x: '',
          y: '',
          settingItems: []
        }
      },
      // 获取隧道示意图
      async getTunnelData() {
        try {
          let obj = { id: 1 }
          let res = await tunnel('get', obj, true)
          if (res.code === 200) {
            if (res.data.useTemplate) {
              if (res.data.templateName === '单洞') {
                this.mapUrl = this.singleHole
              } else if (res.data.templateName === '双洞') {
                this.mapUrl = this.doubleHole
              }
              this.mapSwaitch = false
            } else {
              this.mapSwaitch = true
              this.mapUrl = res.data.backedImageName
            }
          }
        } catch (err) {
          this.mapUrl = ''
          // this.$message.error('隧道示意图查询失败！')
        }
      },
      // 基站图片
      async getBaseStationImage() {
        try {
          let res = await parameter('get', { parameterName: 'BaseStationImage' })
          if (res.code === 200) {
            this.iconData[0].value = res.data.value
            this.iconData[0].id = res.data.id
          }
        } catch (err) {
          // 基站图片
          this.iconData[0].value = assetsImages.baseStation
          // this.$message.error('基站图标查询失败，已使用默认图标！')
        }
      },
      // 监控图片
      async getMonitorImage() {
        try {
          let res = await parameter('get', { parameterName: 'MonitorImage' })
          if (res.code === 200) {
            this.iconData[1].value = res.data.value
            this.iconData[1].id = res.data.id
          }
        } catch (err) {
          // 监控设备
          this.iconData[1].value = assetsImages.camera
          // this.$message.error('监控图标查询失败，已使用默认图标！')
        }
      },
      // 环境监测设备图片
      async getAccessControlImage() {
        try {
          let res = await parameter('get', { parameterName: 'AccessControlImage' })
          if (res.code === 200) {
            this.iconData[2].value = res.data.value
            this.iconData[2].id = res.data.id
          }
        } catch (err) {
          // 环境监测图片
          this.iconData[2].value = assetsImages.sensor
        }
      },
      // 请求图标
      async getIcon() {
        this.imgUrl = assetsImages.camera
        await this.getBaseStationImage()
        await this.getMonitorImage()
        await this.getAccessControlImage()
      },
      // 请求其他设备
      async getEquipment() {
        try {
          let resList = await tunnelRealTime()
          // 处理基站数据
          this.handleBaseStation(resList.data.baseStation)
          // 处理监控数据
          this.handleVedioData(resList.data.videos)
          // 门禁闸机
          this.handleGates(resList.data.gates)
          // 环境检测设备
          this.handleEnvironmental(resList.data.environmentTrackings)
        } catch (err) {
          let er = err
          // this.$message.error('数据查询失败！')
        }
      },
      // 环境检测设备
      handleEnvironmental(value) {
        if (value.lenght === 0) {
          return
        }
        this.environmentalList = value.map((item, index) => {
          return {
            name: item.name,
            x: item.x,
            y: item.y,
            id: item.id + 'a',
            ip: item.ip,
            code: item.code,
            settingItems: item.settingItems // 监测项
          }
        })
      },
      // 基站
      handleBaseStation(value) {
        if (value.lenght === 0) {
          return
        }
        // 获取基站数据
        this.baseStationList = value.map((item, index) => {
          if (item.lenght === 0) {
            return
          }
          return {
            name: item.name,
            id: index + 'b',
            x: item.xPosition,
            y: item.yPosition,
            status: item.status,
            areaName: item.area ? item.area.name : '无',
            siteType: item.siteType === 1 ? '进基站' : item.siteType === 2 ? '出基站' : '其它基站',
            isForWorkCheck: item.isForWorkCheck,
            // 基站范围宽度
            widthPosition: item.widthPosition,
            // 基站范围高度
            heightPosition: item.heightPosition,
            // 基站范围左侧距离
            leftPosition: item.leftPosition,
            // 基站范围顶部距离
            topPosition: item.topPosition,
            // 基站范围旋转角度
            rotate: item.rotate
          }
        })
      },
      // 门禁闸机
      handleGates(value) {
        if (value.lenght === 0) {
          return
        }
        // 获取闸机数据
        this.gatesList = value.map((item, index) => {
          return {
            name: item.name,
            x: item.xPosition,
            y: item.yPosition,
            id: index + 'c',
            // rotate: item.rotate,
            areaName: item.area ? item.area.name : '无',
            siteType: item.siteType === 1 ? '进基站' : item.siteType === 2 ? '出基站' : '其它基站',
            isForWorkCheck: item.isForWorkCheck,
            // 范围宽度
            widthPosition: item.widthPosition,
            // 范围高度
            heightPosition: item.heightPosition,
            // 范围左侧距离
            leftPosition: item.leftPosition,
            // 范围顶部距离
            topPosition: item.topPosition,
            // 范围旋转角度
            rotate: item.rotate
          }
        })
      },
      // 处理监控
      handleVedioData(value) {
        if (value.lenght === 0) {
          return
        }
        this.videoList = value.map(item => {
          return item
        })
      },
      // 取随机数
      random(min, max) {
        return Math.floor(Math.random() * (max - min + 1) + min)
      },
      getCoordinateHandler(event) {
        let map = document.querySelector('#map')
        let dialog = this.$refs['el-dialog']
        // 获取鼠标在浏览器中的位置
        let mousex = event.clientX
        let mousey = event.clientY
        // 获取盒子位置
        let elementx = map.offsetLeft + dialog.$refs.dialog.offsetLeft
        let elementy = map.offsetTop + dialog.$refs.dialog.offsetTop - dialog.$el.scrollTop
        // 获取鼠标在盒子中的位置
        this.formData.x = (mousex - elementx) * 1.5
        this.formData.y = (mousey - elementy) * 1.5
      }
    }
  }
</script>

<style lang="scss" scoped>
  .alert-label {
    width: 160px;
    text-align: center;
  }
  .alert-value {
    width: 80px;
  }
  .labelDiv {
    display: flex;
    .deep {
      color: #000;
      // width: 120px;
      text-align: left;
    }
    .shallow {
      padding-right: 10px;
      color: #666;
      width: 70px;
      text-align: right;
    }
    .shallowTwo {
      display: inline-block;
      width: 70px;
      height: 100%;
      text-align: right;
    }
  }
  .divTwo {
    width: 802px;
    height: 402px;
    margin-left: 20px;
    margin-bottom: 20px;
    border: 1px solid #ccc;
    position: relative;
    background-color: #ccc;
    .messg {
      position: absolute;
      top: -32px;
      left: 0px;
      color: red;
    }
    .mapImg {
      width: 100%;
      height: 100%;
    }
    .divS {
      width: 20px;
      height: 20px;
      display: none;
      position: absolute;
      border-radius: 50%;
      transform: translate(-50%, -50%);
      background-color: #fff;
      img {
        width: 100%;
        height: 100%;
        float: left;
      }
    }
    .range {
      display: inline-block;
      position: absolute;
      border: 1px solid lime;
    }
    .up {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      position: absolute;
      display: inline-block;
      background-color: #fff;
      transform: translate(-50%, -50%);
      img {
        float: left;
        width: 100%;
        height: 100%;
      }
    }
    .cameraItem {
      z-index: 100;
      width: 20px;
      height: 20px;
      left: 0;
      top: 0;
      border-radius: 50%;
      position: absolute;
      display: inline-block;
      background-color: #fff;
      img {
        width: 100%;
        height: 100%;
        float: left;
      }
    }
  }
</style>
